
include( 'shared.lua' )
include( 'cl_scroll.lua' )

local tohide = { -- This is a table where the keys are the HUD items to hide
	["CHudHealth"] = true,
	["CHudBattery"] = true,
	["CHudAmmo"] = true,
	["CHudZoom"] = true,
	["CHudDamageIndicator"] = true,
	["CHudCrosshairs"] = true,
	["CHudWeapon"] = true,
	["CHudSecondaryAmmo"] = true
}
local function HUDShouldDraw(name) -- This is a local function because all functions should be local unless another file needs to run it
	if (tohide[name]) then     -- If the HUD name is a key in the table
		return false;      -- Return false.
	end
end
hook.Add("HUDShouldDraw", "removedefault", HUDShouldDraw)


function customTab()
	return false
end
hook.Add("HUDDrawScoreBoard", "CustomTab", customTab)

function noPickup( item )
	return false
end 
hook.Add( "HUDItemPickedUp", "NotifyMe", noPickup)
hook.Add( "HUDWeaponPickedUp", "noguns", noPickup)

c_sprays = {}
function IncomingHook( handler, id, encoded, decoded )
	c_sprays = decoded  
end
datastream.Hook( "sprays", IncomingHook )
eDown = false
shoot_time = 0
ball_holder = nil
function pfHud()
    local client = LocalPlayer()
	local tr = client:GetEyeTrace()
	local tb_w,tb_h = 200, 60
	--surface.CreateFont ("Arial", 40, 400, true, false, "CV20")
	--surface.SetFont("Arial")
	surface.SetFont( "DefaultBold" )
	surface.SetDrawColor(50,50,50,255) -- gray drawing color
	draw.RoundedBox(3, ScrW()/2 - tb_w/2, 20 ,tb_w , tb_h, Color(50,50,50,255)) 
	local tw = surface.GetTextSize("Red Team: "..team.GetScore(1))
	local tw2 = surface.GetTextSize("Blue Team: "..team.GetScore(2))
	--local tw3 = surface.GetTextSize("Score to win: "..GetConVar("pf_maxscore"))

    draw.SimpleText("Red Team: "..team.GetScore(1), "DefaultBold", (ScrW() / 2) - tw/2,  40, Color(255, 0, 0, 255),0, 1)
    draw.SimpleText("Blue Team: "..team.GetScore(2), "DefaultBold", (ScrW() / 2) - tw2/2,  60, Color(0, 0, 255, 255),0, 1)
    --draw.SimpleText("Score to win: "..GetConVar("pf_maxscore"), "Arial", (ScrW() / 2) - tw3/2,  80, Color(0, 0, 255, 255),0, 1)
	
	
    if !client:Alive() then return end
	local str = ""
	if(client:Frags() == 1) then
		str = "You have 1 kill" 
	else
		str = "You have "..client:Frags().." kills"
	end
	local TextWidth = surface.GetTextSize(str)
	local TextWidth2 = surface.GetTextSize("Health: "..client:Health() .. "HP")
	local TextWidth3 = surface.GetTextSize("Scroll to change your prop!")
	--local act_m = client:GetNWString("prop") or "models/Combine_Helicopter/helicopter_bomb01.mdl"
	--local act_m = client:GetNWString("prop") or "models/Combine_Helicopter/helicopter_bomb01.mdl"
	local TextWidth4 = surface.GetTextSize("Time until next fire: "..shoot_time)
    draw.RoundedBox(3, (ScrW() / 2) - 140, ScrH() - 100, 280, 94, Color(55, 55, 55, 155))
    draw.SimpleText("Scroll to change your prop!", "DefaultBold", (ScrW() / 2) - TextWidth3/2,  ScrH() - 80, Color(255, 255, 255, 255),0, 1)
    draw.SimpleText(str, "DefaultBold", (ScrW() / 2) - TextWidth/2,  ScrH() - 60, Color(255, 255, 255, 255),0, 1)
	
	--health bar
	local HP = client:Health()
	local MaxHP = math.max(client:Health(),1000)

	local x , y , w , h = ScrW()/2-(TextWidth2+20)/2 , ScrH() - 48 , math.max(100,TextWidth2+20) , 18
	
	surface.SetDrawColor(team.GetColor(client:Team())) -- orange-ish tint
	surface.DrawRect(x+2 , y+2 , HP/MaxHP*w-4 , h-4) -- foreground box / healthbar
    draw.SimpleText("Health: "..client:Health() .. "HP", "DefaultBold", (ScrW() / 2) - TextWidth2 / 2, ScrH() - 40, Color(255, 255, 255, 255),0, 1)
	
    draw.SimpleText("Time until next fire: "..shoot_time, "DefaultBold", (ScrW() / 2) - TextWidth4 / 2, ScrH() - 20, Color(255, 255, 255, 255),0, 1)
	local x = ScrW() / 2
	local y = ScrH() / 2
	 
	--set the drawcolor
	surface.SetDrawColor(team.GetColor(LocalPlayer():Team()))
	 
	local gap = 4
	local length = gap + 12
	 
	--draw the crosshair
	surface.DrawLine( x - length, y, x - gap, y )
	surface.DrawLine( x + length, y, x + gap, y )
	surface.DrawLine( x, y - length, x, y - gap )
	surface.DrawLine( x, y + length, x, y + gap )


	for k,v in pairs(c_sprays) do
		local dis = (LocalPlayer():GetEyeTrace().HitPos - v.pos):Length()
		local dis2 = (LocalPlayer():GetPos() - v.pos):Length()
		local vec = (v.pos + v.ang * 3):ToScreen()
		local ply = player.GetByUniqueID(k)

		if dis < 50 and dis2 < 125 then
			if(LocalPlayer():KeyPressed(IN_USE) and eDown == false and LocalPlayer():IsAdmin()) then
				--chat.AddText("You pressed e on "..ply:Nick().."'s spray!")
				RunConsoleCommand("spray_kick", ply:Nick())
				eDown = true
			elseif(LocalPlayer():KeyReleased( IN_USE ) ) then
				eDown = false
			end
				
			-- cam.Start3D2D( v.pos + v.ang*3, v.ang*90, 1 )
				-- draw.DrawText(ply:Nick().."'s spray", "DefaultBold", 0, 0, Color(255, 255, 255, 255), TEXT_ALIGN_CENTER )
			-- cam.End3D2D()
			local nick = ply:Nick().."'s spray" or "Disconnected"
			draw.SimpleText(nick, "DefaultBold", vec.x, vec.y, Color(255, 255, 255, 255),1, 1)
		end
	end
	
	
	for k,v in pairs(ents.FindByClass("pf_ball")) do
		local dis = math.floor((LocalPlayer():GetShootPos() - v:GetPos()):Length())
		local vec = (v:GetPos() + Vector(0,0,24) ):ToScreen()
		draw.SimpleText("Ball", "DefaultBold", vec.x, vec.y, Color(255, 255, 255, 255),1, 1)
		draw.SimpleText(""..dis.."ft", "DefaultBold", vec.x, vec.y+16, Color(255, 255, 255, 255),1, 1)
	end
	
	if(ball_holder != nil) then
		for k,v in pairs(player.GetAll()) do
			if v == ball_holder then
				local vec = (v:GetPos() + Vector(0,0,72) ):ToScreen()
				draw.SimpleText("Has ball", "DefaultBold", vec.x, vec.y, Color(255, 255, 255, 255),1, 1)
			end
		end
	end
		
	for k,v in pairs(player.GetAll()) do
		local dis = (LocalPlayer():GetShootPos() - v:GetShootPos()):Length()
		local vec = ( v:GetShootPos() + Vector(0,0,24) ):ToScreen()
		if(LocalPlayer() != v and v:Team() != 3 and !v:Crouching()) then
			DrawPlayerBar( v , vec.x , vec.y, math.max(0,(0.8-(dis/2000)) * 255) )
		end
	end
	
	
	if(tr.Entity:GetClass() == "prop_ragdoll" and tr.Entity:IsValid() and !tr.Entity:IsWorld()) then
		drawRagInfo(tr.Entity)
	end	

end
hook.Add("HUDPaint", "pfhud", pfHud)




function drawRagInfo(rag)
	local owner = rag:GetOwner()
	if !owner:IsPlayer() then return end
	local wid = surface.GetTextSize(owner:Nick().." 's corpse.")
	surface.CreateFont ("Arial", 28, 400, true, false, "CV20")
	draw.SimpleText( owner:Nick().." 's corpse." , "Arial" , (ScrW()/2) - wid/2, ScrH()/2 + 60 , team.GetColor(owner:Team()) , 0 , 1)
	
end

function DrawPlayerBar(p,XOff,YOff,alpha)

	if !p then return end
	if !p or !p:IsValid() or !p:IsPlayer() then return end
	local str = p:Nick()
	-- store the size of the text were going to be drawing
	--surface.CreateFont ("Arial", 28, 400, true, false, "CV20")
	surface.SetFont( "DefaultBold" )

	local tw,th = surface.GetTextSize(str)
	-- get the players health
	local HP = p:Health()
	local MaxHP = math.max(p:Health(),1000)
	-- replace 1000 till I can find a clientside function to get the players max health.. -_-*

	local x , y , w , h = XOff-(tw+20)/2 , YOff , math.max(100,tw+20) , th+6
	
	local bgcol = team.GetColor(p:Team())
	surface.SetDrawColor(50,50,50,alpha) -- gray drawing color
	surface.DrawRect(x , y , w , h) -- background box
	
	surface.SetDrawColor(bgcol.r,bgcol.g,bgcol.b,alpha) -- orange-ish tint
	surface.DrawRect(x+2 , y+2 , HP/MaxHP*w-4 , h-4) -- foreground box / healthbar
	-- draw some interesting text centered to the bar
	draw.SimpleText( str , "DefaultBold" , x+w/2 , y+h/2 , Color(255,255,255,alpha) , 1 , 1)
	
	--surface.SetTexture(ExampleTex)
	--surface.SetDrawColor(255,255,255,alpha)
	--surface.DrawTexturedRect( x+2,y+2, w-5,h-4 )
end


local TextParticles = {}
hook.Add("HUDPaint","killtext", function()
	--surface.CreateFont ("Arial", 28, 400, true, false, "CV20")
	surface.SetFont( "DefaultBold" )

	for k,v in pairs(TextParticles) do
		if v ~= nil then
			local vec = v.pos:ToScreen()
			draw.SimpleText(v.text, "DefaultBold", vec.x,vec.y, v.color, 1,1)
			v:update()
		end
	end
end)

function addText(text, pos, col)
    local tmp = {
        pos = pos,
        vel = Vector(0,0,0.25),
        text = text,
        life = 0,
        maxlife = 50,
        color = col or Color(255,255,255,255),
    }
    function tmp:update()
        self.pos = self.pos + self.vel
        self.life = self.life + 1
        if self.life >= self.maxlife then
            table.remove(TextParticles,k)
        end
    end
    TextParticles[#TextParticles+1] = tmp
end

usermessage.Hook("dmgText",function(um)
	local ent = um:ReadEntity()
	local dmg = um:ReadShort()
	local pos = um:ReadVector()
	
	local col = team.GetColor(ent:Team())
	addText("-"..tostring(dmg), pos, col)
end)


 
function set_team() 
	frame = vgui.Create( "DFrame" )
	local w,h,bw,bh = 120, 190, 100, 40
	frame:SetPos( (ScrW() / 2) - w / 2 , (ScrH() / 2) - h / 2 ) //Set the window in the middle of the players screen/game window 
	frame:SetSize( w, h ) //Set the size 
	frame:SetTitle( "Change Team" ) //Set title 
	frame:SetVisible( true ) 
	frame:SetDraggable( false ) 
	frame:ShowCloseButton( true ) 
	frame:MakePopup() 

	team_1 = vgui.Create( "DButton", frame ) 
	team_1:SetPos( (w/2) - bw / 2, 40 )
	team_1:SetSize( bw, bh ) 
	team_1:SetText( "Red("..team.NumPlayers(1)..")") 
	team_1.DoClick = function()
		RunConsoleCommand( "team_1" ) 
		frame:Remove()
	end 

	team_2 = vgui.Create( "DButton", frame ) 
	team_2:SetPos( (w/2) - bw / 2, 90 )
	team_2:SetSize( bw, bh ) 
	team_2:SetText( "Blue("..team.NumPlayers(2)..")") 
	team_2.DoClick = function()
		RunConsoleCommand( "team_2" ) 
		frame:Remove()
	end 
	
	team_2 = vgui.Create( "DButton", frame ) 
	team_2:SetPos( (w/2) - bw / 2, 140 )
	team_2:SetSize( bw, bh ) 
	team_2:SetText( "Spectator("..team.NumPlayers(2)..")" ) 
	team_2.DoClick = function()
		RunConsoleCommand( "team_3" ) 
		frame:Remove()
	end 

end 
concommand.Add( "team_menu", set_team ) 


function kickMenu(ply, cmd, args) 
	frame = vgui.Create( "DFrame" )
	local w,h,bw,bh = 220, 140, 200, 40
	frame:SetPos((ScrW() / 2) - w / 2 , (ScrH() / 2) - h / 2 )
	frame:SetSize( w, h ) //Set the size 
	frame:SetTitle( "Would you like to kick...") 
	frame:SetVisible( true ) 
	frame:SetDraggable( false ) 
	frame:ShowCloseButton( true ) 
	frame:MakePopup() 

		
	la = vgui.Create( "DLabel", frame ) 
	la:SetPos( 12, 22 )
	la:SetColor(Color(255,255,255,255)) 
	la:SetText( args[1]) 
	la:SizeToContents()
	
	yes = vgui.Create( "DButton", frame ) 
	yes:SetPos( (w/2) - bw / 2, 40 )
	yes:SetSize( bw, bh ) 
	yes:SetText( "Yes" ) 
	yes.DoClick = function()
		RunConsoleCommand( "ulx", "kick", args[1], "Spray" ) 
		frame:Remove()
	end 

	no = vgui.Create( "DButton", frame ) 
	no:SetPos( (w/2) - bw / 2, 90 )
	no:SetSize( bw, bh ) 
	no:SetText( "No" ) 
	no.DoClick = function()
		frame:Remove()
	end 

end 
concommand.Add( "spray_kick", kickMenu ) 


/* UM */
function propCount( um )
	chat.AddText(Color(255,255,255), "There are "..um:ReadShort().." prop(s)")
end
usermessage.Hook("prop_count", propCount)

function ballHolder(um)
	local ply = um:ReadEntity()
	ball_holder = ply
	chat.AddText(team.GetColor(ply:Team()), ply:Nick(), Color(255,255,255), " has the ball!")
end
usermessage.Hook("ball_holder", ballHolder)
	
	
function roundEndResults( um )
	local teamnum = um:ReadShort()
	chat.AddText(Color(255,255,255), "The ", team.GetColor(teamnum), team.GetName(teamnum).." team", Color(255,255,255), " has won the round!")
	-- timer.Simple(5, function()
		
	-- end)
end
usermessage.Hook("winner_msg", roundEndResults)


function playerHurt( um )
	vic = um:ReadEntity()
	attk = um:ReadEntity()
	--chat.AddText(Color(255,255,0), "[DMG] ", Color(255,255,255), vic:Nick().." was hurt by ", Color(255, 255, 255), attk:GetOwner())
end
usermessage.Hook("hurt_log", playerHurt)

function playerDeath( um )
	vic = um:ReadEntity()
	attk = um:ReadEntity()
	if(attk:IsPlayer() and vic:IsPlayer()) then
		chat.AddText(team.GetColor(vic:Team()), vic:Nick(), Color(255,255,255), " was killed by ", team.GetColor(attk:Team()), attk:Nick())
	end
end
usermessage.Hook("death_log", playerDeath)


function fireDelay( um )
	time = um:ReadShort()
	local x = 0
	timer.Create("fire_msg", 1, 0, function()
		--chat.AddText("Cant fire!")
		x = x + 1
		shoot_time = time - x
	end)	
	timer.Simple(time, function()
		timer.Stop("fire_msg")
		shoot_time = 0
	end)
end
usermessage.Hook("fire_delay", fireDelay)


